'/
' MOTEP - Massive Online Text Environment Project
' --------------------------------------------------------------------------------
' MOTEP Master Server
' 
' Main.bmx
' 
' (c) Anton Berlin. All Rights Reserved.
'/

strict

import bah.raknet

include "Main_h.bmx"
include "..\Shared\Strings.bmx"
include "..\Shared\ADL.bmx"
include "..\Shared\NetUtil.bmx"
include "..\Shared\MessageIdentifiers.bmx"
include "Master.bmx"

AppTitle = APP_TITLE '// Set application title.
main() '// Call the main function.



' ==============================================================================
' Main function.
' ==============================================================================
function main()

	'// Set the random seed to milliseconds.
	SeedRnd(MilliSecs())
	
	' Open the log stream for writing.
	if (FileType(LOG_FILE) = 0) then
		local success:int = CreateFile(LOG_FILE)
		if (not success) RuntimeError("Could not create file ~q" + LOG_FILE + "~q.")
	end if
	logHandle = WriteStream(LOG_FILE)
	if (not logHandle) then
		RuntimeError("Could not load ~q" + LOG_FILE + "~q to memory.")
		return 0
	end if
	
	' Initialize the master object.
	Master.Initialize()
	
	' Create the server peer.
	masterPeer = TRKRakNetworkFactory.GetRakPeerInterface()
	
	' Startup the network threads.
	local s:TRKSocketDescriptor = TRKSocketDescriptor.CreateSocketDescriptor(MASTER_PORT)
	masterPeer.Startup(MAX_CONNECTIONS, 30, s)
	masterPeer.SetMaximumIncomingConnections(MAX_CONNECTIONS)
	
	' Load the account database.
	write("Loading database ~qADL\accounts.adl~q...")
	AccountDatabase.LoadADL("ADL\accounts.adl")
	
	' In case everything went fine.
	write("MasterServer created successfully. Starting to listen for connections (port " + MASTER_PORT + ").")
	write("Press <CTRL+C> to exit.")
	
	' Main loop.
	while (not Master.m_stopEvent and not AppTerminate())
		Delay(10) ' Let other applications get CPU power as well.
		Master.Run()
	end while
	
	' Save the account database.
	AccountDatabase.SaveADL("accounts.adl")
	
	' End the log.
	outLog(DOUBLE_DASH_BAR)
	outLog("MasterServer ended: " + CurrentTime() + " " + CurrentDate())
	
	' Close server.
	if (masterPeer) then
		masterPeer.Shutdown(peerShutdownTime)
		TRKRakNetworkFactory.DestroyRakPeerInterface(masterPeer)
	end if
	
	' Close the log stream.
	CloseStream(logHandle)
end function

' Write a line into the log.
function outLog(str:string)
	WriteLine(logHandle, str)
end function

' Write to the standard output AND to the log.
function write(str:string)
	outLog(str)
	Print(str)
end function
